package net.vkits.controller;

import net.vkits.common.Utils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by ethan-liu on 16/3/24.
 */
@Controller
@RequestMapping("/")
public class LoginController {

    @RequestMapping("/")
    public String index() {
        return "redirect:/login";
    }

    @RequestMapping(value = "login", method = RequestMethod.GET)
    public String showLoginForm() {
        return "/login";
    }

    @RequestMapping(value = "login", method = RequestMethod.POST, produces = "text/html; charset=utf-8")
    public String login(HttpServletRequest request, Model model) {
        final Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            return "redirect:/main";
        }
        String exceptionClassName = (String) request.getAttribute("shiroLoginFailure");
        String error = null;
        if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
            error = "用户名/密码错误";
        } else if (IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
            error = "用户名/密码错误";
        } else if (exceptionClassName != null) {
            error = "其他错误：" + exceptionClassName;
        }
        model.addAttribute("error", error);
        return showLoginForm();
    }

    @RequestMapping(value = "logout", produces = "text/html; charset=utf-8")
    public String logout() {
        SecurityUtils.getSubject().logout();
        return "redirect:/login";
    }

    @RequestMapping(value = "main")
    public ModelAndView main() {
        String username = Utils.getUsername(SecurityUtils.getSubject()).orElse("Null");
        ModelMap modelMap = new ModelMap();
        modelMap.put("treeview", "");
        modelMap.put("sidebar", "main");
        modelMap.put("currentUser", username);
        return new ModelAndView("/main", modelMap);
    }
}
